<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="600px" :title="`${drawerProps.title}用户`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="用户头像" prop="avatarUrl">
        <UploadImg
          v-model:image-url="drawerProps.row!.avatarUrl"
          width="135px"
          height="135px"
          :file-size="3"
          :prefix-data="AVATAR"
        >
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传头像</span>
          </template>
          <template #tip> 头像大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <!-- <el-form-item label="用户照片" prop="photo">
        <UploadImgs v-model:file-list="drawerProps.row!.photo" height="140px" width="140px" border-radius="50%">
          <template #empty>
            <el-icon><Picture /></el-icon>
            <span>请上传照片</span>
          </template>
          <template #tip> 照片大小不能超过 5M </template>
        </UploadImgs>
      </el-form-item> -->
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="drawerProps.row!.mobile" placeholder="请填写手机号" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="状态" prop="status">
        <el-select v-model="drawerProps.row!.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in drawerProps.userStatus" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="drawerProps.row!.roleId" :multiple="true" placeholder="请选择角色" clearable>
          <el-option v-for="item in drawerProps.userRoleList" :key="item.name" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属公司" prop="companyId">
        <el-select v-model="drawerProps.row!.companyId" placeholder="请选择所属公司" clearable @change="changeCompany">
          <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.companyId" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="departmentIdTemp" v-if="drawerProps.row!.companyId">
        <el-cascader
          v-model="drawerProps.row!.departmentIdTemp"
          :options="departmentList"
          :props="{ checkStrictly: true, value: 'id', label: 'name', children: 'departmentModels' }"
          clearable
        />
      </el-form-item>
      <el-form-item label="用户名" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="请填写用户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="drawerProps.title == '新增'">
        <el-input type="password" v-model="drawerProps.row!.password" placeholder="请填写用户密码" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="drawerProps.row!.sex" placeholder="请选择性别" clearable>
          <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="drawerProps.row!.email" placeholder="请填写邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="省市区" prop="address">
        <el-cascader v-model="drawerProps.row!.address" :options="areaList" clearable :props="defaultOptions" ref="cascaderRef" />
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="总积分" prop="totalIntegral">
        <el-input v-model="drawerProps.row!.totalIntegral" placeholder="请填写总积分" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="冻结积分" prop="iceIntegral">
        <el-input v-model="drawerProps.row!.iceIntegral" placeholder="请填写冻结积分" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.row!.remark" placeholder="请填写备注" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item v-show="drawerProps.isView" label="修改人" prop="modifiedBy">
        <el-input v-model="drawerProps.row!.modifiedBy" placeholder="请填写备注" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="修改时间" prop="gmtModified">
        <el-input v-model="drawerProps.row!.gmtModified" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="创建人" prop="createBy">
        <el-input v-model="drawerProps.row!.createBy" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="创建时间" prop="gmtCreate">
        <el-input v-model="drawerProps.row!.gmtCreate" placeholder="" clearable></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="详细地址" prop="address">
        <el-input v-model="drawerProps.row!.address" placeholder="请填写居住地址" clearable></el-input>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, onMounted } from "vue"; // getCurrentInstance
import { genderType } from "@/utils/serviceDict";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage, FormInstance, CascaderInstance } from "element-plus";
import { User, Dict, Role, Area } from "@/api/interface";
import { Customer } from "@/api/interface/customer";
import UploadImg from "@/components/Upload/Img.vue";
import { getProvince, getCity, getDistrict } from "@/api/modules/sys"; //getDict
import { getDepartment } from "@/api/modules/organization";
import { AVATAR } from "@/constants";
import mittBus from "@/utils/mittBus";
import { getCompanyDepart } from "@/api/modules/customer";
let companyList: Customer.ResCustomerData[] = reactive([]);
// const cxt = getCurrentInstance();
// const dict = cxt?.appContext.config.globalProperties.$dict;
// import { get } from "@/api/modules/sys"; // exportUserInfo,BatchAddUser
// import UploadImgs from "@/components/Upload/Imgs.vue";
const areaList: Area[] = ref();
const cascaderRef = ref<CascaderInstance>();
const userStore = useUserStore();
let departmentList = ref([]);
// 省市区
const defaultOptions = {
  checkStrictly: true,
  lazy: true,
  label: "name",
  value: "code",
  lazyLoad: async (node: Node, resolve: (data: Area) => void) => {
    let data = [];
    if (node.level === 1) {
      data = await getCitys({ code: node.data.code });
    } else if (node.level === 2) {
      data = await getDistricts({ code: node.data.code });
    }
    data = data.map(item => {
      item.leaf = node.level >= 2;
      return item;
    });
    resolve(data);
  }
};
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {
    roleId: []
  },
  userStatus: [],
  userRoleList: []
});
// const validatePass = (rule: any, value: any, callback: any) => {
//   console.log(value);
//   callback();
// };
const rules = reactive({
  avatarUrl: [{ required: true, message: "请上传用户头像" }],
  mobile: [{ required: true, pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: "请填写手机号" }],
  totalIntegral: [{ required: false, pattern: /^[0-9]+$/, message: "只能为数字" }],
  iceIntegral: [{ required: false, pattern: /^[0-9]+$/, message: "只能为数字" }],
  name: [{ min: 0, max: 10, trigger: "blur", message: "用户名0-10位之间" }],
  status: [{ required: false, message: "请选择状态" }],
  roleId: [{ required: true, message: "请选择角色" }],
  email: [{ required: false, message: "请填写邮箱" }],
  password: [
    {
      required: true,
      pattern: /^[A-Za-z0-9]{8,18}$/,
      message: "密码必须由字母、数字组成，区分大小写, 8-18位"
    }
  ]
});
// : reactive({
//     avatar: [{ required: true, message: "请上传用户头像" }],
//     mobile: [{ required: true, pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: "请填写手机号" }],
//     totalIntegral: [{ required: false, pattern: /^[0-9]+$/, message: "只能为数字" }],
//     iceIntegral: [{ required: false, pattern: /^[0-9]+$/, message: "只能为数字" }],
//     name: [{ min: 0, max: 10, trigger: "blur", message: "用户名0-10位之间" }],
//     status: [{ required: false, message: "请选择状态" }],
//     roleId: [{ required: true, message: "请选择角色" }],
//     email: [{ required: false, message: "请填写邮箱" }]
//   });

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  userStatus: Dict.ResDictList[];
  userRoleList: Role.ReqRoleParams[];
}

const drawerVisible = ref(false);

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  params.row.roleId = params.row.roleId || [];
  drawerProps.value = params;
  drawerVisible.value = true;
  if (params.row.companyId) {
    getDepartmentFn({ companyId: params.row.companyId });
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      console.log(drawerProps.value.row!.address);
      // 校验
      // if (drawerProps.value.row.username.length > 10) {
      //   ElMessage.error({ message: "用户名不能大于10位" });
      //   return;
      // }
      // 部门
      drawerProps.value.row!.departmentId = drawerProps.value.row!.departmentIdTemp?.pop();
      delete drawerProps.value.row!.departmentIdTemp;
      delete drawerProps.value.row!.companyId;
      // 省市区传值处理
      if (drawerProps.value.row!.address && drawerProps.value.row!.address.length) {
        let arrAddress = cascaderRef.value.getCheckedNodes();
        let names = arrAddress[0]["pathLabels"];
        let value = drawerProps.value.row!.address;
        drawerProps.value.row.province = names[0];
        drawerProps.value.row.provinceCode = value[0];
        drawerProps.value.row.city = names[1];
        drawerProps.value.row.cityCode = value[1];
        drawerProps.value.row.district = names[2];
        drawerProps.value.row.districtCode = value[2];
      }
      delete drawerProps.value.row.address;
      await drawerProps.value.api!(drawerProps.value.row);
      // 处理省市区的传值
      ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
      // 如果当前编辑是自己
      if (drawerProps.value.row.id && userStore.userInfo.id === drawerProps.value.row.id) {
        mittBus.emit("refreshUserInfo");
      }
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
const getCitys = async (params: Area) => {
  const { data } = await getCity(params);
  return data || [];
};
const getDistricts = async (params: Area) => {
  const { data } = await getDistrict(params);
  return data || [];
};
const getDepartmentFn = async params => {
  try {
    const { data } = await getDepartment(params);
    if (data) {
      departmentList.value = data;
      console.log(departmentList);
    }
  } catch (e) {
    console.log(e);
  }
};
// 公司
const changeCompany = item => {
  getDepartmentFn({ companyId: item });
  // const companyLists = companyList.find(itm => itm.id === item);
  // drawerProps.value.row.parentCompanyName = companyLists?.name;
};
// 获取全部公司
const getCompanyListFn = async () => {
  const { data } = await getCompanyDepart();
  companyList = data || [];
};
onMounted(async () => {
  // 获取省份
  const result = await getProvince();
  areaList.value = result.data;
  getCompanyListFn();
  // if (drawerProps.value.title != "新增") {
  //   rules.password = [];
  // } else {
  //   rules.password =
  // }
  // ruleFormRef.value && ruleFormRef.value.clearValidate();
});
</script>
